<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8"%>
<%@ page import="java.util.*" %>
<%@ page import="bcnet.service.PriceHistoryService" %>
<%@ page import="bcnet.service.factory.PriceHistoryServiceFactory" %>
<%@ page import="bcnet.domain.CodeVO" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.google.appengine.api.memcache.MemcacheService" %>
<%@ page import="com.google.appengine.api.memcache.MemcacheServiceFactory" %>
<%@ page import="com.google.appengine.api.memcache.ErrorHandlers" %>
<%@ page import="java.util.logging.Level" %>
<%
	Calendar cal = Calendar.getInstance();
	cal.add(Calendar.HOUR, +8);
	Date todayDate = cal.getTime();
	
	boolean force = request.getParameter("force")==null?false:Boolean.getBoolean(request.getParameter("force"));
	
	int dow = cal.get (Calendar.DAY_OF_WEEK);
	boolean isWeekday = ((dow >= Calendar.MONDAY) && (dow <= Calendar.FRIDAY));
	
	if(isWeekday || force){
		PriceHistoryService priceHistoryService = PriceHistoryServiceFactory.getPriceHistoryService();
		String runningStatus = priceHistoryService.getRunningStatus();
	
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
	
		String buyList = (String) syncCache.get("buyList");
		String sellList = (String) syncCache.get("sellList");
		
		if(runningStatus.equals("Not running") && buyList != null && sellList != null){
			
			String mailSent = (String) syncCache.get("mailSent");
			if(mailSent == null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// send the buy/sell list
				priceHistoryService.sendMail("bunchannet "+sdf.format(todayDate), "BuyList:<br/>"+(String) syncCache.get("buyList")+"<br/><br/>SellList:<br/>"+(String) syncCache.get("sellList"));
				// check if already bought, send another email to remind to sell
				String sellBoughtCode = priceHistoryService.sellBoughtCode();
				if(sellBoughtCode == null || "".equals(sellBoughtCode)){
					out.println("No bought code to sell");
					// do nothing
				}
				else{
					priceHistoryService.sendMail("Sell "+sdf.format(todayDate), sellBoughtCode);
					out.println(sellBoughtCode);
				}
				syncCache.put("mailSent",sdf.format(todayDate));
			}
		}
	}		
%>
